/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package abricots.net;

import com.esotericsoftware.kryonet.Connection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author charly
 */
public class ServerConnectionsHandler {
    // maps per connection id

    private final Map<Integer, ServerConnection> connections;

    public ServerConnectionsHandler() {
        connections = new HashMap<Integer, ServerConnection>();
    }

    public Set<Integer> getConnectionsIds() {
        return new HashSet<Integer>(connections.keySet());
    }

    public ServerConnection getConnection(int id) {
        return connections.get(id);
    }

    public void addConnection(ServerConnection connection) {
        connections.put(connection.getID(), connection);
    }

    public void removeConnection(Connection handler) {
        connections.remove(handler.getID());
    }

    public long getOldestAckedTime() {
        long oldestTime = -1;
        for (ServerConnection connection : connections.values()) {
            long time = connection.getAckedFramesManager().getLastAckedTime();
            if (time < 0) {
                continue;
            }
            if (oldestTime < 0) {
                oldestTime = time;
                continue;
            }
            if (oldestTime > time) {
                oldestTime = time;
            }
        }
        return oldestTime;
    }

    public long getMostRecentReceivedCommandsTime() {
        long cmdTime = -1;
        for (ServerConnection connection : connections.values()) {
            long time = connection.getLastReceivedCommandTime();
            if (time < 0) {
                continue;
            }
            if (cmdTime < 0) {
                cmdTime = time;
                continue;
            }
            if (cmdTime < time) {
                cmdTime = time;
            }
        }
        return cmdTime;
    }
}
